package com.example.resultinterceptor.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.util.List;


/**
 * 结果拦截器配置类
 * 支持灵活的URL匹配和配置
 *
 * @author luojiawei
 */
@Data
@ConfigurationProperties(prefix = "result-advice")
@Configuration
public class ResultAdviceConfig {

    /**
     *
     * 配置示例:将配置放在application.yml中或者直接代码中配置属性
     # 拦截器配置文件
     result-advice:
     enabled: true
     internal-error-msg: "数据库操作失败，请联系管理员"

     # URL拦截配置
     intercept-urls:
     - "/**"

     # JDBC错误关键词
     jdbc-error-keywords:
     - "SQLException"
     - "SQLSyntaxErrorException"
     - "SQLIntegrityConstraintViolationException"
     - "MyBatisException"
     - "PersistenceException"
     - "DataAccessException"
     - "BadSqlGrammarException"
     - "DataIntegrityViolationException"
     - "DuplicateKeyException"
     - "QueryTimeoutException"
     - "MySQLSyntaxErrorException"
     - "CommunicationsException"
     - "PSQLException"
     - "SQL"

     */
    private boolean enabled=true;
    private String internalErrorMsg=
            "数据库操作失败，请联系管理员";
    private List<String> interceptUrls=
            List.of("/**");
    private List<String> jdbcErrorKeywords=
            List.of("SQLException",
                    "SQLSyntaxErrorException",
                    "SQLIntegrityConstraintViolationException",
                    "MyBatisException",
                    "PersistenceException",
                    "DataAccessException",
                    "BadSqlGrammarException",
                    "DataIntegrityViolationException",
                    "DuplicateKeyException",
                    "QueryTimeoutException",
                    "MySQLSyntaxErrorException",
                    "CommunicationsException",
                    "PSQLException",
                    "SQL");
    /**
     * 检查URL是否应该被拦截
     */
    public boolean shouldIntercept(String requestUri) {
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String urlPattern : interceptUrls) {
            if (pathMatcher.match(urlPattern, requestUri)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查错误信息是否包含JDBC相关关键词
     */
    public boolean containsJdbcError(String errorMessage) {
        if (errorMessage == null || errorMessage.isEmpty()) {
            return false;
        }
        String lowerCaseError = errorMessage.toLowerCase();
        for (String keyword : jdbcErrorKeywords) {
            if (lowerCaseError.contains(keyword.toLowerCase())) {
                return true;
            }
        }
        return false;
    }
}
